import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useAdminUserStore } from "@/store/adminUser"
import LoginPage from '@/pages/LoginIndex.vue'
import NotFoundPage from '@/pages/404.vue'
import { useMenuStore } from "@/store/menu"

const routes = [
    {path: '/login', name: "Login", component: LoginPage},
    {path: '/:pathMatch(.*)*', name: '404', component: NotFoundPage}
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {
    const adminUserStore = useAdminUserStore()
    const menuStore = useMenuStore()

    if (import.meta.env.VITE_APP_MODE === 'static') {
        NProgress.start()
        if (!menuStore.initStatus) {
            await menuStore.init()
            await menuStore.menuInitializedPromise
            next(to.fullPath); // 重新触发导航
        } else {
            menuStore.addNavMenu(to.path)
            next()
        }
    } else {
        let tokenInfo = adminUserStore.tokenInfo;
        if (tokenInfo == null && to.name !== "Login") {
            router.replace("/login").then(() => {})
        } else if (to.name === "Login" && tokenInfo != null) {
            router.replace("/").then(() => {})
        } else {
            NProgress.start()
            if (!menuStore.initStatus && adminUserStore.tokenInfo) {
                await menuStore.init()
                await menuStore.menuInitializedPromise
                next(to.fullPath); // 重新触发导航
            } else {
                menuStore.addNavMenu(to.path)
                next()
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

export default router
